package cas.ihep.spark.rdd;

import cas.ihep.spark.util.NamedResourceManager;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class NamedResourceManagerImpl extends HashMap<String,Object> implements NamedResourceManager,Closeable {
    private Set<Closeable> resources;
    private boolean closed;
    NamedResourceManagerImpl(){
        resources=new HashSet<>();
        closed=false;
    }

    public Object get(String key){
        return super.get(key);
    }

    @Override
    public Object put(String key, Object value) {
        Object ret=super.put(key,value);
        if(value instanceof Closeable){
            resources.add((Closeable)value);
        }
        return ret;
    }

    @Override
    public Object remove(Object o) {
        Object value=super.remove(o);
        if(value instanceof Closeable){
            resources.remove(value);
        }
        return value;
    }

    @Override
    public void putAll(Map<? extends String, ?> map) {
        for(Map.Entry<?extends String,?> entry:map.entrySet()){
            Object value=entry.getValue();
            super.put(entry.getKey(),value);
            if(value instanceof Closeable){
                resources.add((Closeable)value);
            }
        }
    }

    @Override
    public void clear() {
        resources.clear();
    }

    @Override
    public void close() throws IOException {
        if(closed){
            return;
        }
        IOException threw=null;
        for(Closeable c:resources){
            try {
                c.close();
            }catch (IOException e){
                if(threw==null){
                    threw=e;
                }else{
                    threw.addSuppressed(e);
                }
            }
        }
        closed=true;
        if(threw!=null){
            throw threw;
        }
    }
}
